package com.cloudm.technician.ui.modules.cloudm_box.upload_level_pic

import com.cloudm.technician.data.db.DbHelper
import com.cloudm.technician.data.model.ImageInfo
import com.cloudm.technician.data.model.UploadTokenInfo
import com.cloudm.technician.data.network.CloudmBoxApi
import com.cloudm.technician.data.network.CommonApi
import com.cloudm.technician.data.preferences.PreferencesHelper
import com.cloudm.technician.extensions.buildUploadTokenKey
import com.cloudm.technician.ui.base.RxPresenter
import com.qiniu.android.storage.UpCompletionHandler
import com.qiniu.android.storage.UpProgressHandler
import com.qiniu.android.storage.UploadManager
import com.qiniu.android.storage.UploadOptions
import io.reactivex.Observable
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.File

/**
 * 作者: wesley
 * 时间: 2017/12/23
 * 描述: 业务逻辑
 */
class UploadLevelPicPresenter(private val view: UploadLevelPicContract.View,
                              private val cloudmBoxApi: CloudmBoxApi,
                              private val commonApi: CommonApi,
                              private val uploadManager: UploadManager,
                              private val preferencesHelper: PreferencesHelper,
                              private val dbHelper: DbHelper) : RxPresenter(),
        UploadLevelPicContract.Presenter {


    override fun buildImageInfo() {
        val list: ArrayList<ImageInfo> = arrayListOf(ImageInfo(0, "", "液位节点\n近景照"),
                ImageInfo(0, "", "液位线束"))
        view.buildImageInfoSuccess(list)
    }


    override fun buildImageFromLocal(deviceId: Int) {
        view.buildImageInfoSuccess(dbHelper.queryLocalImage(preferencesHelper.userId, 1, deviceId))
    }

    override fun updateLocalImage(position: Int, url: String, deviceId: Int, flag: Int) {
        dbHelper.updateLocalImage(preferencesHelper.userId, 1, deviceId, position, url, flag)
    }

    override fun updateClearImage(deviceId: Int) {
        dbHelper.clearLocalImage(preferencesHelper.userId, 1, deviceId)
    }

    override fun onItemClick(info: ImageInfo, position: Int) {
        when (info.flag) {
            0 -> view.takePic(position)
            1 -> view.showLoadingMsg(position, info.url)
            2 -> view.openPicPreviewActivity(position, info.url)
        }
    }

    override fun getUploadToken(file: File, position: Int) {
        request(commonApi.getUploadInfo(), view, onSuccess = { info, _ ->
            when (info) {
                null -> {
                    view.showTokenInfoEmpMsg()
                    view.updateUiByFlag(0, position)
                }
                else -> {
                    view.loadTokenInfoSuccess(info, file, position)
                }
            }
        }, onFailure = { errorMsg ->
            view.showErrorMsg(errorMsg)
            view.updateUiByFlag(0, position)
        })
    }

    override fun uploadFile(info: UploadTokenInfo, file: File, position: Int) {
        Observable.create(ObservableOnSubscribe<String> { e ->
            uploadManager.put(file, buildUploadTokenKey(), info.uptoken,
                    UpCompletionHandler { key, responseInfo, _ ->
                        if (responseInfo == null || !responseInfo.isOK) {
                            e.onNext("")
                            return@UpCompletionHandler
                        }
                        e.onNext(info.origin + key)
                    }, UploadOptions(null, null, false, UpProgressHandler { _, percent ->
                view.showUploadPercent(position, percent)
            }, null))
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe { url ->
            if (url == null || url.isNullOrEmpty()) {
                view.picUploadFailure()
                view.updateUiByFlag(0, position)
            } else {
                view.picUploadSuccess(url, position)
            }
        }
    }

    override fun uploadLevelPic(deviceId: Int, recordId: String?, list: ArrayList<ImageInfo>) {
        if (list.size < 2) {
            view.showUnknowError()
            return
        }
        if (list[0].flag != 2) {
            view.showLevelPicMsg()
            return
        }
        if (list[1].flag != 2) {
            view.showLevelWireMsg()
            return
        }

        request(cloudmBoxApi.uploadOilPhoto(deviceId, list[0].url, list[1].url, recordId), view,
                onSuccess = { _, _ ->
                    view.hideUploadDialog()
                    updateClearImage(deviceId)
                    if (recordId == null || recordId.isNullOrEmpty()) {
                        view.openChannelListActivity()
                    } else {
                        view.openReplaceSuccessActivity()
                    }
                }, onFailure = { errorMsg ->
            view.hideUploadDialog()
            view.showUploadLevelFailureMsg(errorMsg)
        })
    }
}